package com.wu.rocketmq_demo.demo;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;


import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author benjamin_5
 * @Description 顺序发送
 * @date 2024/6/7
 */
public class Producer3OrderDemo {

    public static void main(String[] args) throws Exception{
        DefaultMQProducer producer = new DefaultMQProducer("group_test");
        // 声明namesrv地址
        producer.setNamesrvAddr("localhost:9876");
        // 设置重试次数
        producer.setRetryTimesWhenSendFailed(2);
        // 启动实例
        producer.start();


        // 要求发送顺序：i为偶数先发，然后按照由小到大顺序发送
        for (int i = 0; i < 10; i++) {
            // 模拟偶数、奇数分别属于一类消息
            int orderId = i % 2;

            // 设置消息的topic,tag以及消息体
            Message msg = new Message("topic_order", "tag_test", ("消息内容"+i).getBytes(StandardCharsets.UTF_8));

            SendResult result = producer.send(msg, new MessageQueueSelector() {
                /**
                 *
                 * @param list 消息队列集合
                 * @param message 消息
                 * @param arg send方法中传入的第三参数，即orderId参数，orderId可以是Object类型
                 * @return
                 */
                @Override
                public MessageQueue select(List<MessageQueue> list, Message message, Object arg) {
                    Integer orderId = (Integer) arg;
                    int index = orderId % list.size();
                    return list.get(index);
                }
            }, orderId);
            System.out.println("发送结果："+result.toString());
        }
        producer.shutdown();
    }
}
